var googlejsapi = {};

googlejsapi.keys = {
  'http://as-is.net/':
    'ABQIAAAA2SGB7kYAwJ7vNIiGUvsYgBQBbqWMXPd7ku0BIuG8sIWAUrc4NRSFo9YNTIVrCt2PqV-iwm2ShFyasQ',
  'http://as-is.net/blog/':
    'ABQIAAAA2SGB7kYAwJ7vNIiGUvsYgBTtdpswgWQA1981Rv_CA-cfvjtwURRF2uyescpcxSD27PBh-FFvVnSRUQ'
};

googlejsapi.is_loaded = function() {
  if (typeof google == 'undefined' ||
      typeof google.load == 'undefined' ||
      typeof google.setOnLoadCallback == 'undefined')
    return false;

  googlejsapi.is_loaded = function() { return true; };
  return true;
};

googlejsapi.show_search = function(id) {
  if (!googlejsapi.is_loaded())
    return;
  if (typeof GSearch == 'undefined')
    google.load("search", "1.0");
  document.write('<div id="' + id + '"><img src="loading.gif" alt="Loading..." width="24" height="24" /></div>');

  google.setOnLoadCallback(function() {
    var e = document.getElementById(id);
    if (e) {
      var searchControl = new GSearchControl();
      var siteSearch = new GwebSearch();
      siteSearch.setUserDefinedLabel("Site Search");
      siteSearch.setUserDefinedClassSuffix("siteSearch");
      siteSearch.setSiteRestriction("as-is.net");
      searchControl.addSearcher(siteSearch);
      searchControl.addSearcher(new GwebSearch());
      var drawOptions = new GdrawOptions();
      drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);
      searchControl.draw(e, drawOptions);
    }
  });
};

googlejsapi.show_feed = function(id, url, count) {
  if (!googlejsapi.is_loaded())
    return;
  if (typeof google.feeds == 'undefined')
    google.load('feeds', '1');

  document.write('<div id="' + id + '"><img src="loading.gif" alt="Loading..." width="24" height="24" /></div>');

  google.setOnLoadCallback(function() {
    var feed = new google.feeds.Feed(url);
    feed.setNumEntries(count || 10);
    feed.load(function(result) {
      if (!result.error) {
        var container = document.getElementById(id);
        var text = '';
        for (var i = 0; i < result.feed.entries.length; i++) {
          var entry = result.feed.entries[i];
          text += '<li><a href="' + entry.link + '">' + entry.title + '</a></li>';
        }
        container.innerHTML = '<ul>' + text + '</ul>';
      }
    });
  });
};

// load script
(function() {
  var url = location.href;
  var idx;
  while ((idx = url.lastIndexOf('/')) != -1) {
    url = url.substring(0, idx);
    var key = googlejsapi.keys[url + '/'];
    if (key) {
      document.write('<script type="text/javascript" src="http://www.google.com/jsapi?key=' + key + '"></script>');
      return;
    }
  }
})();
